import { Button, Input, Message, Select } from '@arco-design/web-react';
import AddressParse from 'address-parse';
import { useEffect, useState } from 'react';
import { ValidateRule } from '../../../types';
import DetailItem from '../../../components/detailItem';
import DetailModal from '../../../components/detailModal';
import LoadingMask from '../../../components/loadingMask';
import { areaList, cityList, cloneDeep, provinceList, validateField } from '../../../utils/utils';
import { apiGetCardUserAddressList,apiUpdateCardDetailConvertDetail } from '../../../api';
import { CardUserAddress } from '../../../types';
import { CardDetailConvert } from './types';
interface Props {
  id: string;
  cardId?: number;
  userId?: number | string;
  iccid?: string;
  onCancel: (update?: boolean) => void;
}

// 字段验证规则
const rule: ValidateRule = {
  iccid: { required: true, message: '旧卡号必填' },
  provinceName: { required: true, message: '省份必填' },
  cityName: { required: true, message: '城市必填' },
  countyName: { required: true, message: '县/区必填' },
  receiverAddress: { required: true, message: '收件地址必填' },
  receiverName: { required: true, message: '收件人必填' },
  receiverPhone: { required: true, regexp: /^1[2-9]{1}[0-9]{9}$/, message: '联系电话格式错误' },
  expressNo: { required: 'status', status: 'waitSignFor', message: '快递单号必填' },
  expressName: { required: 'status', status: 'waitSignFor', message: '快递名称必填' },
  newIccid: { required: 'status', status: 'waitTransferCard', message: '新卡号必填' },
};

export default function CardDetailConvertDetailPage({ id, iccid, cardId, userId, onCancel }: Props) {
  // 页面标题 显示在二级菜单下面
  const pageTitle = id === 'create' ? '转卡申请' : '转卡换卡';
  // 每次编辑时修改的数据
  const [detailData, setDetailData] = useState<CardDetailConvert | null | undefined>({
    iccid,
    cardId,
    status: 'audit',
  });
  // 数据验证结果
  const [errorData, setErrorData] = useState<{ [x: string]: string }>({});

  // 当前详情 根据id的值区分页面模式
  const [detail, setdetail] = useState<{  [x: string]: any }>({});
  // --------------额外数据--------------------------------------
  //自动识别地址填写的内容
  const [readAddress, setReadAddress] = useState('');
  // -----------------------------------------------------------
  // 页面初次渲染时获取数据
  useEffect(() => {
    if (id && id !== 'create') {
      // handleRefreshData();
    }
    // if (id === 'create' && checkPermission('card:cardUserAddress:list')) {
    //   loadAddress();
    // }
  }, []); //eslint-disable-line

  // 页面详情数据获取到后存入编辑数据
  useEffect(() => {
    if (id !== 'create' && detail?.loaded && detail?.result) {
      let result = detail?.result;
      setDetailData(result);
      // setDetailData(Object.assign({}, result, { remark: '' }));
      // 需要依赖详情数据加载别的数据的 在这里写
    }
  }, [detail]); //eslint-disable-line

  
  // 任意字段修改时存入编辑数据
  function handleChange(key: string, value: any, secondKey?: string, secondValue?: any) {
    let data: any = cloneDeep(detailData);
    data[key] = value;
    if (key === 'provinceName') {
      data.cityName = '';
      data.countyName = '';
    } else if (key === 'cityName') {
      data.countyName = '';
    }
    if (secondKey) {
      data[secondKey] = secondValue;
    }
    setDetailData(data);
  }
  // 保存
  async function handleSave() {
    let validateRes = validateField(detailData, rule);
    setErrorData(validateRes);
    if (Object.keys(validateRes).length) return;

    LoadingMask.show('正在保存...');
    try {
      let res = await apiUpdateCardDetailConvertDetail(id!, detailData ?? {});
      let data = res.data;
      if (data.code === 200) {
        Message.success({ id: 'save', content: '保存成功' });
        onCancel(true);

        // handleRefreshData(true);
      } else {
        Message.warning({ id: 'save', content: data.msg ?? '保存失败' });
      }
    } catch (e: any) {
      Message.error({ id: 'save', content: e.message ?? '保存失败' });
    } finally {
      LoadingMask.hide();
    }
  }
  //----------------额外操作 / 数据-------------------
  // 加载用户默认地址
  async function loadAddress() {
    try {
      let res = await apiGetCardUserAddressList(1, 1000, { userId, status: 'Y' });
      let data = res.data;
      if (data.code === 200) {
        if (data.rows.length) {
          let defaultAddress: CardUserAddress = data.rows[0];
          if (defaultAddress) {
            setDetailData(
              Object.assign({}, detailData, {
                provinceName: defaultAddress.provinceName,
                cityName: defaultAddress.cityName,
                countyName: defaultAddress.countyName,
                receiverName: defaultAddress.receiverName,
                receiverPhone: defaultAddress.receiverPhone,
                receiverAddress: defaultAddress.receiverAddress,
              })
            );
          }
        }
      } else {
        Message.warning({ id: 'save', content: data.msg ?? '保存失败' });
      }
    } catch (e: any) {
      Message.error(e.message ?? '加载默认地址失败');
    }
  }

  // 开始识别地址
  async function handleReadAddress() {
    let [res] = AddressParse.parse(readAddress, true);
    if (res) {
      let _data = Object.assign({}, detailData, {
        provinceName: res.province,
        cityName: res.city,
        countyName: res.area,
        receiverName: res.name,
        receiverPhone: res.mobile ?? res.phone,
        receiverAddress: res.details,
      });
      setDetailData(_data);
    }
  }

  //-------------------------------------------------

  return (
    <DetailModal className="bw-80" title={pageTitle} show onConfirm={handleSave} onCancel={() => onCancel()}>
      {id === 'create' && (
        <div className="d-flex-c ai-center bw-100 mb-20">
          <Input.TextArea
            className="m-input flex-1 mb-20"
            placeholder="请粘贴地址信息，如果识别不准确，请在姓名和手机号左右加逗号"
            autoSize={{ minRows: 2 }}
            value={readAddress}
            onChange={setReadAddress}
          />
          <Button type="primary" onClick={handleReadAddress}>
            识别
          </Button>
        </div>
      )}
      <DetailItem label="旧充值卡号" required labelSpan={12} outlet={2} error={errorData?.iccid}>
        <Input
          className="m-input"
          value={detailData?.iccid}
          disabled={id !== 'create'}
          onChange={(v) => handleChange('iccid', v)}
        />
      </DetailItem>
      {id !== 'create' && (
        <DetailItem
          label="新充值卡号"
          required={detailData?.status === 'waitTransferCard'}
          labelSpan={12}
          outlet={2}
          error={errorData?.newIccid}
        >
          <Input
            className="m-input"
            value={detailData?.newIccid}
            disabled
            onChange={(v) => handleChange('newIccid', v)}
          />
        </DetailItem>
      )}

      <DetailItem label="收件人" required labelSpan={12} outlet={2} error={errorData?.receiverName}>
        <Input className="m-input" value={detailData?.receiverName} onChange={(v) => handleChange('receiverName', v)} />
      </DetailItem>
      <DetailItem label="联系电话" required labelSpan={12} outlet={2} error={errorData?.receiverPhone}>
        <Input
          className="m-input"
          value={detailData?.receiverPhone}
          onChange={(v) => handleChange('receiverPhone', v)}
        />
      </DetailItem>
      <DetailItem label="省" required labelSpan={12} outlet={2} error={errorData?.provinceName}>
        <Select
          className="m-select"
          showSearch
          filterOption={(inputValue, option) =>
            option.props.value.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0 ||
            option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
          }
          options={provinceList()}
          value={detailData?.provinceName}
          onChange={(v) => handleChange('provinceName', v)}
        />
      </DetailItem>
      <DetailItem label="市" required labelSpan={12} outlet={2} error={errorData?.cityName}>
        <Select
          className="m-select"
          showSearch
          filterOption={(inputValue, option) =>
            option.props.value.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0 ||
            option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
          }
          options={cityList(detailData?.provinceName)}
          value={detailData?.cityName}
          onChange={(v) => handleChange('cityName', v)}
        />
      </DetailItem>
      <DetailItem label="县/区" required labelSpan={12} outlet={2} error={errorData?.countyName}>
        <Select
          className="m-select"
          showSearch
          filterOption={(inputValue, option) =>
            option.props.value.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0 ||
            option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
          }
          options={areaList(detailData?.provinceName, detailData?.cityName)}
          value={detailData?.countyName}
          onChange={(v) => handleChange('countyName', v)}
        />
      </DetailItem>
      <DetailItem label="收件地址" required labelSpan={6} outlet={4} error={errorData?.receiverAddress}>
        <Input.TextArea
          className="m-input"
          autoSize={{ minRows: 2 }}
          value={detailData?.receiverAddress}
          onChange={(v) => handleChange('receiverAddress', v)}
        />
      </DetailItem>

      {id !== 'create' && (
        <DetailItem
          label="快递单号"
          required={detailData?.status === 'waitSignFor'}
          labelSpan={12}
          outlet={2}
          error={errorData?.expressNo}
        >
          <Input
            className="m-input"
            value={detailData?.expressNo}
            disabled
            onChange={(v) => handleChange('expressNo', v)}
          />
        </DetailItem>
      )}
      {id !== 'create' && (
        <DetailItem
          label="快递名称"
          required={detailData?.status === 'waitSignFor'}
          labelSpan={12}
          outlet={2}
          error={errorData?.expressName}
        >
          <Input
            className="m-input"
            value={detailData?.expressName}
            disabled
            onChange={(v) => handleChange('expressName', v)}
          />
        </DetailItem>
      )}
      {/* <DetailItem label="状态" required labelSpan={4} outlet={4} error={errorData?.status}>
        <Select
          className="m-select"
          options={dictDataOptions(dictDatas[CARD_DETAIL_CONVERT_STATUS])}
          value={detailData?.status}
          onChange={(v) => handleChange('status', v)}
        />
      </DetailItem> */}
      {/* <DetailItem label="图片" labelSpan={12} outlet={2} error={errorData?.customerImg}>
        <UploadImg
          values={detailData?.customerImg ? detailData?.customerImg!.split(';') : []}
          onlyReturnUrl
          disabled={id !== 'create'}
          onChange={(v) => handleChange('customerImg', v?.length ? v[0] : '')}
        />
      </DetailItem> */}
      <DetailItem label="换卡说明" labelSpan={6} outlet={4} error={errorData?.customerDesc}>
        <Input.TextArea
          className="m-input"
          maxLength={200}
          showWordLimit
          disabled={id !== 'create'}
          value={detailData?.customerDesc}
          autoSize={{ minRows: 2 }}
          onChange={(v) => handleChange('customerDesc', v)}
        />
      </DetailItem>
      <DetailItem label="备注" labelSpan={6} outlet={4} error={errorData?.remark}>
        <Input.TextArea
          className="m-input"
          maxLength={200}
          showWordLimit
          value={detailData?.remark}
          autoSize={{ minRows: 2 }}
          onChange={(v) => handleChange('remark', v)}
        />
      </DetailItem>
    </DetailModal>
  );
}
